import api from "@/api";
import { set, remove } from "@/utils/store";

export default {
  namespaced: true, // 模块
  state() {
    return {
      userinfo: {},
      // token: null,
    };
  },
  getters: {},
  mutations: {
    changeUserinfo(state, payload) {
      state.userinfo = payload;
    },
  },
  actions: {
    // 登陆
    // payload --> 一整个数据  123    { username, password } -> obj { username, password}
    async login({ commit }, { username, password }) {
      try {
        let {
          data: { user, token },
        } = await api.login({ username, password });
        commit("changeUserinfo", user);
        set("zmall", token); // 存token
      } catch (err) {
        return Promise.reject(err);
      }
    },
    // 退出登陆  自己考虑退出登陆使用的位置
    async logout({ commit }) {
      try {
        await api.logout();
        commit("changeUserinfo", {});
        remove("zmall");
      } catch (err) {
        return Promise.reject(err);
      }
    },

    // 获取用户信息
    async getUser({ commit }) {
      try {
        let { data } = await api.user();
        commit("changeUserinfo", data);
      } catch (err) {
        return Promise.reject(err);
      }
    },

    // 修改信息  payload: id(用户的id)   可能包含{username  nickname  phone  email}
    async editUser({ commit }, payload) {
      try {
        let { data } = await api.edituser(payload);
        commit("changeUserinfo", data);
      } catch (err) {
        return Promise.reject(err);
      }
    },
  },
};
